<?php

namespace App\Services\Admin\Other;

use App\Exceptions\OtherException;
use Exception;

class SettingService extends BaseOtherService
{
    /**
     * 配置列表
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function list(array $params): array
    {

        $total = $this->getSettingModel()->count();

        // 查询配置列表
        $settingList = $this->getSettingModel()->list([
            'alias', 'title', 'values'
        ]);

        $list = [];
        foreach ($settingList as $item) {
            $list[] = [
                'alias' => $item['alias'],
                'title' => $item['title'],
                'values' => json_decode($item['values'], true)
            ];
        }

        return [
            'total' => $total,
            'list' => $list,
        ];
    }

    /**
     * 更新配置
     * @return void
     * @throws Exception
     */
    public function update($params)
    {
        // 查询配置
        $setting = $this->getSettingModel()->getAliasValue($params['alias']);
        if (empty($setting)) {
            throw new OtherException("配置不存在", OtherException::CODE_1002);
        }

        $updateData['values'] = json_encode($params['values']);
        // 更新配置
        $this->getSettingModel()->updateItemByAlias($params['alias'], $updateData);
    }
}
